package com.yang.springcloud.controller;

import com.yang.springcloud.pojo.CommonResult;
import com.yang.springcloud.pojo.Payment;
import com.yang.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class PaymentController {

    /** 注入 服务发现 */
    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;


    @PostMapping(value = "/payment/create")
    // 这个的 @RequestBody 在测试 provider 的时候可以不写
    // 但是通过 RestTemlate 远程访问该方法时，就要加上了，不然识别不到该参数
    public CommonResult create(@RequestBody Payment payment){
//    public CommonResult create(Payment payment){
        int result = paymentService.create(payment);
        log.info("*****插入结果："+result);
        if (result>0){  //成功
            return new CommonResult(200,"插入数据库成功",result);
        }else {
            return new CommonResult(444,"插入数据库失败",null);
        }
    }
    @GetMapping(value = "/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") long id){
        Payment payment = paymentService.getPaymentById(id);
        log.info("*****查询结果："+payment);
        if (payment!=null){  //说明有数据，能查询成功
            return new CommonResult(200,"【端口：】"+ serverPort +"---【查询成功】",payment);
        }else {
            return new CommonResult(444,"没有对应记录，查询ID："+id,null);
        }
    }

    /** 暴露查询自己相关信息的接口 */
    @GetMapping(value = "/payment/discovery")
    public Object discovery(){
        // 获取服务列表清单
        List<String> services = discoveryClient.getServices();
        for (String element : services) {
            log.info("***** element:"+element);
        }
        // 获得指定的微服务名称对应的实例
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info("ServiceId : " + instance.getServiceId()+"\n"+
                    "Host : " + instance.getHost()+"\n" +
                    "Port :" + instance.getPort()+"\n"+
                    "Uri : " + instance.getUri());
        }
        return this.discoveryClient;
    }


    /** 用于测试自定义负载均衡 */
    @GetMapping(value = "/payment/lb")
    public String getPaymentLB(){
        return serverPort;
    }


    //超时设置，8001程序故意设置暂停程序,暂停3秒钟
    @GetMapping(value = "/payment/feign/timeout")
    public String paymentFeignTimeout(){
        try {
            TimeUnit.SECONDS.sleep(3);
        }catch (InterruptedException e){ e.printStackTrace();  }
        return serverPort;
    }




}
